/**
 *  TextMash - simple IDE for Clojure
 *  
 *  Copyright (C) 2010 Aleksander Naszko
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package pl.olek.jruce;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.SocketTimeoutException;
import java.util.logging.Logger;

/**
 *
 * @author anaszko
 */
public abstract class GroupReceiver {

    final public static Logger logger = Logger.getLogger(GroupReceiver.class.getName());

//    final private static HashSet<GroupReceiver> listeners = new HashSet<GroupReceiver>();
    public abstract void receive(InetSocketAddress incomingAddress, InputStream input) throws Exception;
    Daemon daemon;

    public GroupReceiver(String groupName) {

        try {

            final MulticastSocket socket = new MulticastSocket(extractPort(groupName));

            final InetAddress address = InetAddress.getByName(extractIp(groupName));

            socket.joinGroup(address);

            socket.setSoTimeout(400);

//            synchronized (listeners) {
//                listeners.add(this);
//                listeners.notify();
//            }

            daemon = new Daemon() {

                @Override
                public void run() {

                    try {

                        byte[] buffer = new byte[4096];

                        while (isRunning()) {


//                            synchronized (listeners) {
//                                if (!listeners.contains(GroupReceiver.this)) {
//                                    break;
//                                }
//                            }

                            try {

                                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                                socket.receive(packet);

                                receive(new InetSocketAddress(packet.getAddress(), packet.getPort()),
                                        new ByteArrayInputStream(packet.getData(), 0, packet.getLength()));

                            } catch (SocketTimeoutException e) {
                            }
                        }

                        socket.leaveGroup(address);

                        socket.close();

                    } catch (Exception e) {
//                        logger.log(Level.SEVERE, null, e);
                    }
                }
            };

//            thread.start();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void join(){
        daemon.join();
    }

    public void close() {
        daemon.stop();
////        synchronized (listeners) {
////            listeners.remove(this);
//////            listeners.notify();
////        }
    }

    public static Integer extractPort(String groupName) {
        int code = Integer.MAX_VALUE & groupName.hashCode();
        int result = 1024 + (code % (Short.MAX_VALUE - 1024));
//        logger.info("For group " + groupName + " port=" + result);
        return result;
    }

    public static String extractIp(String groupName) {
        int code = Integer.MAX_VALUE & groupName.hashCode();
        String result = "225." + (code % 225) + "." + ((code / 2) % 225) + "." + ((code / 3) % 225);
//        logger.info("For group " + groupName + " ip=" + result);
        return result;
    }
//    private static void join() {
//        for (;;) {
//            synchronized (listeners) {
//                if (listeners.isEmpty()) {
//                    break;
//                }
//                try {
//                    listeners.wait();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    break;
//                }
//            }
//        }
//    }
//
//    private static void closeAll() {
//        synchronized (listeners) {
//            listeners.clear();
//            listeners.notify();
//        }
//    }
}
